/**
 * Created by hldev on 17-3-13.
 */
import axios from 'axios';
import {Message} from 'element-ui';
import setting from '../../config/setting';
import  Auth from  './auth'
import router from '../../routes/route'

axios.default.timeout = 5000;

// axios.interceptors.request.use(
//     config => {
//         if (Auth.authenticated()) {
//             const token = Auth.getToken();
//             config.headers.common["Authorization"] = `Bearer${token}`;
//         }
//         return config;
//     },
//     err => {
//         return Promise.reject(err)
//     }
// );

axios.interceptors.response.use(
    response => {
        return response
    },
    error => {
        if (error.response) {
            switch (error.response.status) {
                case 401:
                    Auth.logout();
                    router.replace({
                        path: 'login',
                        querry: {redirect: router.currentRoute.fullPath}
                    })
            }
        }
        return Promise.reject(error)
    }
);

export function request(config, success, error, commit) {
    return axios(config)
        .then(function (response) {
            commit(success.type, response.data);
            if (success.message) {
                Message.success({message: success.message, duration: 1000})
            }
        })
        .catch(e => {
            if (error && error.message) {
                Message.error({message: error.message, duration: 1000})
            }
        });

}